<?php

namespace App\Http\Controllers\H5;

use App\Library\User\TreeManager;
use App\Models\Trees;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class TreeController extends BaseController
{
    public function index()
    {
        //dd($this->user()->bubbles()->find(3)->tree);
        TreeManager::releaseBubbles();

        return $this->view('h5.tree.index');
    }

    public function getTrees(Request $request)
    {
        $items = $this->user()->trees()->with('tree')->orderByDesc('id')
            ->get()->map(function ($tree){
                $tree->tree->image = image_url($tree->tree->image);
                $tree->bubbles_left = $tree->bubbles - $tree->bubbles_released;
                $tree->created_at = @date('Y-m-d H:i', $tree->created_at);
                return $tree;
            });
        return ajaxReturn(['items'=>$items]);
    }

    public function buy()
    {

        $wallet = $this->user()->wallet()->firstOrCreate([]);
        $trees = Trees::all()->map(function ($tree){
            $tree->quantity = 0;
            $tree->checked = true;
            $tree->image = image_url($tree->image);
            return $tree;
        });
        return $this->view('h5.tree.buy', compact('wallet', 'trees'));
    }


    public function checkBuy(Request $request)
    {
        $trees = $request->input('trees');
        if ($trees)
        {
            foreach ($trees as $tree)
            {
                TreeManager::buyTree($this->user, $tree['treeid'], $tree['quantity']);
            }
        }
        return ajaxReturn($trees);
    }
}
